import myConfig from '@/myConfig'
import {
    showToast
} from '@/util/toast'
import * as storage from '@/util/storage'
import {tansParams,getCurrentPage} from '@/util/utils'
import BaseRes from "@/api/BaseRes";


//异步请求
export default function request(param: any): Promise {
    const httpDefaultOpts = {
        url: `${myConfig.app.baseUrl}${param.url}`,
        method: param.method || 'post',
		header:{
			"Accept-Language":"zh-CN,zh;q=0.9en;q=0.8",
		}
    }
	if (storage.getToken() && param.isToken) {
	    httpDefaultOpts.header["Authorization"] = 'Bearer ' + storage.getToken()
	}
		
	if(param.method === 'post' || param.method === 'put'){
		httpDefaultOpts.data = param.data || {}
	}else if(param.method === 'get' && param.params){
		let url = httpDefaultOpts.url + '?' + tansParams(param.params);
		url = url.slice(0, -1);
		httpDefaultOpts.params = {};
		httpDefaultOpts.url = url;    
	}
	
    return new Promise((resolve, reject) => {
        uni.request(httpDefaultOpts).then((response: any) => {
            const data = response.data
            if (data.code !== 200) {
                handleError(data)
            }
            resolve(data)
        }).catch((response: any) => {
            showToast(response, 'none', 1000, false) //'未知错误'
        })
    })
}

function handleError(data: any) {
    const {
        code,
        msg,
		success
    } = data
	if(success){
		showToast(msg, "success", 2000, false)
	}else{
		setTimeout(()=>{
			showToast(msg, "none", 2000, false)
		},1000)
	}
	
}

// function handleError(data: any) {
//     const {
//         code,
//         msg
//     } = data
//     if (code === '') {}
//     showToast(msg, null, 2000, false)
// }
